package com.atgion.gateway.utis;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * JwtToken生成的工具类
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME = "username";

    private static final String CLAIM_KEY_CREATED = "created";

    @Value("secret")
    private String secret;

    @Value("expiration")
    private String expiration;

    @Value("tokenHeader")
    private String tokenHeader;

    @Value("tokenHead")
    private String tokenHead;

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 从token中获取登录用户名
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    public String getUserNameFromToken(String token) {
        String username;
        try {
            String redisKey = tokenHead + token;
            String userInfoFromRedis = redisTemplate.opsForValue().get(redisKey);
            // 2. 验证token是否过期
            if (!isTokenExpired(token)||userInfoFromRedis == null) {
                return null;
            }else{
                Claims claims = getClaimsFromToken(token);
                username = claims.get(CLAIM_KEY_USERNAME, String.class);
            }
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return !expiredDate.before(new Date());
    }
    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }


}
